package com.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.bean.Daobean;
import com.bean.Sqlmap;
import com.bean.Struts;
import com.bean.XML;




/**
 * 
 * <p>功能描述:xml操作类:主要用户添加xml节点</p>
 * @author  <a href="mailto: zhuyoulong@gmail.com">zhuyoulong</a>
 * @create_date 2008-11-8
 * @version $ Revision: 1.0
 */
public class XMLParse {
	private static final Logger logger;
	/**
	 * xml文件全路径
	 */
	private String xml_file_name;

	private String xml_index_dir;

	private static Document document = null;

	private static String encoding = "gbk";

	static {
		logger = Logger.getLogger(com.util.XMLParse.class);
	}
	
	public static String src =ConfigUtil.getMyConfigPropertyValue("src");
	
	public XMLParse(String s) {		
		xml_file_name = s;
		try {
			openDocument();
		} catch (Exception exception) {
			logger.info("openDocument 调用打开失败",
					exception);
		}
	}
	
	public XMLParse(String directory,String filename){
		if(directory==null){
			directory="";
		}
		else{
			directory=directory+"/";
		}
		xml_file_name = src+"/"+directory+filename;
		try {
			openDocument();
		} catch (Exception exception) {
			logger.info("openDocument 调用打开失败",
					exception);
		}
	}
	
	public void openDocument() throws Exception {
		Document document1 = null;
		File file = null;
		try {
			SAXReader saxreader = new SAXReader();
			if (!(new File(xml_file_name)).exists()) {
				if (createXML())
					file = new File(xml_file_name);
			} else {
				file = new File(xml_file_name);
			}
			document1 = saxreader.read(file);
		} catch (Exception exception) {
			logger.info(exception);
			throw new Exception(
					"document 打开xml失败"
							+ exception.toString());
		}
		XMLParse _tmp = this;
		document = document1;
	}
	
	public boolean createXML() {
		boolean flag = false;
		Document document1 = DocumentHelper.createDocument();
		Element element = document1.addElement("struts");
		Element element1 = element.addElement("include");			
		element1.addAttribute("file", "1");
		try {
			saveXML(document1);
			flag = true;
		} catch (Exception exception) {
			logger.info(exception);
		}
		return flag;
	}
	
	/**
	 * 
	 * <p>功能描述：在src下struts.xml文件中添加include文件<br>
	 * 不判重
	 * </p>
	 * @param struts
	 * @return
	 * @throws Exception
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public Struts addStrutsXml(Struts struts) throws Exception {
		try {
//			if ( struts == null || struts.getInclude().equals("") )
//				throw new Exception("include=" + struts.getInclude() + "!");
			/**
			List list = document.selectNodes("//struts/include");
			
			//判断是否重复
			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				Element element = (Element) iterator.next();
				if (element.attribute("file").getValue()
						.equals(struts.getInclude()))
					throw new Exception("include file=" + struts.getInclude()
							+ "\u5DF2\u7ECF\u5B58\u5728!");
			}
*/
			List list1 = document.selectNodes("//struts");
			Iterator iterator1 = list1.iterator();
			if (iterator1.hasNext()) {
				Element element1 = (Element) iterator1.next();
				Element element2 = element1.addElement("include");
				element2.addAttribute("file", struts.getFile());
//				Element element3 = element2.addElement("road-info");
//				element3.setText(struts.roadinfo);
			}
			try {
				saveXML(document);
			} catch (Exception exception1) {
				logger.info("saveXML  保存xml错误.", exception1);
				throw exception1;
			}
		} catch (Exception exception) {
			logger.info(exception);
			throw exception;
		}
		return struts;
	}
	
	
	public Sqlmap addSqlmapXml(Sqlmap sqlmap) throws Exception {
		try {

			List list1 = document.selectNodes("//sqlMapConfig");
			Iterator iterator1 = list1.iterator();
			if (iterator1.hasNext()) {
				Element element1 = (Element) iterator1.next();
				Element element2 = element1.addElement("sqlMap");
				element2.addAttribute("resource", sqlmap.getResource());
			}
			try {
				saveXML(document);
			} catch (Exception exception1) {
				logger.info("saveXML  保存xml错误.", exception1);
				throw exception1;
			}
		} catch (Exception exception) {
			logger.info(exception);
			throw exception;
		}
		return sqlmap;
	}
	
	public Daobean addDaobeanXml(Daobean daobean) throws Exception {
		try {

			List list1 = document.selectNodes("//beans");
			Iterator iterator1 = list1.iterator();
			if (iterator1.hasNext()) {
				Element element1 = (Element) iterator1.next();
				Element element2 = element1.addElement("bean");
				element2.addAttribute("id", daobean.getDaoid());
				element2.addAttribute("class", daobean.getDaoclass());
				element2.addAttribute("parent", daobean.getDaoparent());
				
				Element element3 = element1.addElement("bean");
				element3.addAttribute("id", daobean.getServiceid());
				element3.addAttribute("class", daobean.getServiceclass());
					Element element5 = element3.addElement("property");
					element5.addAttribute("name", daobean.getServicePropertyName());
					element5.addAttribute("ref", daobean.getServiceRef());
					
				Element element4 = element1.addElement("bean");
				element4.addAttribute("id", daobean.getId());
				element4.addAttribute("class", daobean.getClasspath());
				element4.addAttribute("scope", "prototype");
				
					Element element6 = element4.addElement("property");
					element6.addAttribute("name", daobean.getPropertyName());
					element6.addAttribute("ref", daobean.getRef());
					
					Element element7 = element4.addElement("property");
					element7.addAttribute("name", "IBaseService");
					element7.addAttribute("ref", "baseimp");
			}
			try {
				saveXML(document);
			} catch (Exception exception1) {
				logger.info("saveXML  保存xml错误.", exception1);
				throw exception1;
			}
		} catch (Exception exception) {
			logger.info(exception);
			throw exception;
		}
		return daobean;
	}
	
	/**
	 * 
	 * <p>功能描述：通用添加一个单层xml节点</p>
	 * @param xml
	 * @return
	 * @throws Exception
	 * @author:zhuyoulong
	 * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public XML addXml(XML xml) throws Exception {
		try {
			List list1 = document.selectNodes("//"+xml.getSelectNodes());
			Iterator iterator1 = list1.iterator();
			if (iterator1.hasNext()) {
				Element element1 = (Element) iterator1.next();
				Element element2 = element1.addElement(xml.getElement());
				element2.addAttribute(xml.getAttributeName(), xml.getAttributeValue());
			}
			try {
				saveXML(document);
			} catch (Exception exception1) {
				logger.info("saveXML  保存xml错误.", exception1);
				throw exception1;
			}
		} catch (Exception exception) {
			logger.info(exception);
			throw exception;
		}
		return xml;
	}
	
	public synchronized void saveXML(Document document1) throws Exception {
		Object obj = null;
		try {
			OutputFormat outputformat = OutputFormat.createPrettyPrint();
			outputformat.setEncoding(encoding);
			XMLWriter xmlwriter = new XMLWriter(new OutputStreamWriter(
					new FileOutputStream(xml_file_name), encoding),
					outputformat);
			xmlwriter.write(document);
			xmlwriter.close();
		} catch (Exception exception) {
			logger.info(exception);
			throw new Exception("保存xml错误:"
					+ exception.toString());
		}
		
	}
	

	public String getXml_file_name() {
		return xml_file_name;
	}


	public void setXml_file_name(String xml_file_name) {
		this.xml_file_name = xml_file_name;
	}
	
	
	
	public String getSrc() {
		return src;
	}

	public void setSrc(String src) {
		this.src = src;
	}

	public void setEncoding(String s) {
		XMLParse _tmp = this;
		encoding = s;
	}
	
	public static void main(String[] arg){
//		XML xml = new XML();
//		xml.setSelectNodes("sqlMapConfig");
//		xml.setElement("sqlMap");
//		xml.setAttributeName("resource");
//		xml.setAttributeValue("com/sqlmap/aaa-Map.xml");
//		src=ConfigUtil.getConfigPropertyValue("webroot");
//		XMLParse xmlp = new XMLParse("WEB-INF","sqlMapConfig2.xml");
//		xmlp.setEncoding("utf-8");
		
		/**
		Sqlmap sqlmap = new Sqlmap();
		sqlmap.setResource("com/sqlmap/aaa-Map.xml");
		XMLParse.src=ConfigUtil.getConfigPropertyValue("webroot");
		XMLParse xmlp = new XMLParse("WEB-INF","daoBean.xml");
		xmlp.setEncoding("utf-8");
		try {
			xmlp.addSqlmapXml(sqlmap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		
		Daobean daobean = new Daobean();
		daobean.setId("useraction2");
		daobean.setClasspath("com.action.user.UserAction");
		daobean.setPropertyName("IUser");
		daobean.setRef("userimp");
		XMLParse.src=ConfigUtil.getConfigPropertyValue("webroot");
		XMLParse xmlp = new XMLParse("WEB-INF","daoBean.xml");
		xmlp.setEncoding("utf-8");
		try {
			xmlp.addDaobeanXml(daobean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		   
	}
	
}
